package com.authine.cloudpivot.common.extension.customized.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.alibaba.fastjson.JSON;
import com.authine.cloudpivot.common.extension.customized.service.EmpRelatedInfoSyncService;
import com.authine.cloudpivot.common.extension.utils.Constants;
import com.authine.cloudpivot.common.organization.api.*;
import com.authine.cloudpivot.common.organization.model.BaseUser;
import com.authine.cloudpivot.common.organization.model.Department;
import com.authine.cloudpivot.common.organization.model.DepartmentUser;
import com.authine.cloudpivot.common.organization.model.User;
import com.authine.cloudpivot.common.organization.model.enums.GenderType;
import com.authine.cloudpivot.common.organization.model.enums.Status;
import com.yundasys.hrcenter.dto.EmpInfoQueryRespDTO;
import com.yundasys.hrcenter.dto.EmpRelatedInfoRespDTO;
import com.yundasys.hrcenter.dto.PcDepartmentInfoDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author saiwen
 * @date 2021/5/25 14:51
 * description
 */
@Slf4j
@Service
public class EmpRelatedInfoSyncServiceImpl implements EmpRelatedInfoSyncService {
    @Autowired
    private BaseUserServiceI baseUserServiceI;
    @Autowired
    private DepartmentServiceI departmentServiceI;
    @Autowired
    private DepartmentUserServiceI departmentUserServiceI;
    @Autowired
    private UserServiceI userServiceI;

    @Override
    public void syncData(EmpRelatedInfoRespDTO empRelatedInfoRespDTO) throws BizException {
        //校验
        if (null == empRelatedInfoRespDTO) {
            log.error("员工数据为空");
            throw new BizException("员工数据为空");
        }
        String tableName = empRelatedInfoRespDTO.getTableName();
        if (Constants.EMPLOYEE_INFO.equalsIgnoreCase(tableName)) {
            //处理员工增量数据
            log.info("同步kafka员工数据");
            this.employeeSync(empRelatedInfoRespDTO.getEmpInfoQueryRespDTO());
        } else if (Constants.DEPARTMENT_INFO.equalsIgnoreCase(tableName)) {
            //部门增量数据
//            log.info("同步kafka部门数据");
//            this.departmentSync(empRelatedInfoRespDTO.getDepartmentInfoDTO());
        } else {
            log.error("不支持的增量数据类型[{}]", tableName);
            throw new BizException("员工数据为空不支持的增量数据类型["+ tableName +"]");
        }
    }

    /**
     * 员工数据同步
     * @param empInfoQueryRespDTO
     */
    private void employeeSync(EmpInfoQueryRespDTO empInfoQueryRespDTO) throws BizException {
        if (null == empInfoQueryRespDTO) {
            log.error("kafka员工数据为空");
            throw new BizException("kafka员工数据为空");
        }
        //创建baseUser
        sysBaseUser(empInfoQueryRespDTO);

        //创建orgUser
        sysOrgUser(empInfoQueryRespDTO);

        //创建deptUser
        sysDeptUser(empInfoQueryRespDTO);
    }

    /**
     * 用户id和username 都使用韵达传过来的工号
     */
    private void sysBaseUser(EmpInfoQueryRespDTO empInfoQueryRespDTO){
        String empCode = empInfoQueryRespDTO.getEmpCode();  //工号
        //新增or更新userBase数据
        BaseUser userBaseRecord = baseUserServiceI.getById(empCode);
        BaseUser baseUser = new BaseUser();
        if (null == userBaseRecord){
            log.info("新增userBase数据");
            baseUser.setId(empCode);
            baseUser.setUsername(empCode);
            baseUser.setPassword(PasswordEncoderFactories.createDelegatingPasswordEncoder().encode("123456"));
        } else {
            log.info("更新userBase数据");
            BeanUtil.copyProperties(userBaseRecord,baseUser);
            baseUser.setModifiedTime(new Date());
        }
        baseUser.setName(empInfoQueryRespDTO.getRealName());
        baseUser.setMobile(empInfoQueryRespDTO.getPhoneNo());
        baseUser.setBirthday(empInfoQueryRespDTO.getBirthday());
        baseUser.setDeleted(false);
        baseUser.setGender(GenderType.OTHER);
        if (null == userBaseRecord){
            baseUserServiceI.create(baseUser);
        }else{
            baseUserServiceI.update(baseUser);
        }
        log.info("保存user_base数据成功，result is : {}", JSON.toJSONString(baseUser));
    }

    /**
     * 保存dept_user表数据 ID也保存员工工号empCode
     */
    private void sysDeptUser(EmpInfoQueryRespDTO empInfoQueryRespDTO) throws BizException {
        String userId = empInfoQueryRespDTO.getEmpCode();  //工号
        String orgId = empInfoQueryRespDTO.getOrgId();  //部门ID

        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(empInfoQueryRespDTO.getOrgId())) {
            log.error("userId或者orgId为空，不处理dept_user数据");
            throw new BizException("userId或者orgId为空，不处理dept_user数据");
        }
        Department department = departmentServiceI.getById(empInfoQueryRespDTO.getOrgId());
        if(department != null) {
            DepartmentUser deptUserRecord = departmentUserServiceI.getById(userId);
            DepartmentUser deptUser = new DepartmentUser();
            Status status = (empInfoQueryRespDTO.getWorkingState() == 1 || empInfoQueryRespDTO.getWorkingState() == 0) ? Status.ENABLE:Status.DISABLE;
            if (null == deptUserRecord) {
                deptUser.setId(userId);
                deptUser.setDepartmentId(empInfoQueryRespDTO.getOrgId());
                deptUser.setUserId(userId);
                deptUser.setMain(true);
                deptUser.setDeleted(false);
                departmentUserServiceI.create(deptUser);
            } else {
                BeanUtil.copyProperties(deptUserRecord, deptUser);
                deptUser = deptUserRecord;
                deptUser.setModifiedTime(new Date());
                deptUser.setDeleted(false);
                departmentUserServiceI.update(deptUser);
            }
            departmentServiceI.updateDepartmentEmployees(deptUser.getDepartmentId());
            log.info("dept_user数据保存成功, result is : {}", JSON.toJSONString(deptUser));
        }else {
            log.error("未找到部门deptId[{}]对应的数据，不进行dept_user数据的处理", orgId);
        }

    }

    /**
     * 保存org_user表数据 ID保存员工工号empCode

     */
    private void sysOrgUser(EmpInfoQueryRespDTO empInfoQueryRespDTO) throws BizException {
        String empCode = empInfoQueryRespDTO.getEmpCode();  //工号
        String deptId = empInfoQueryRespDTO.getOrgId();  //部门ID

        if (StringUtils.isEmpty(empCode) || StringUtils.isEmpty(empInfoQueryRespDTO.getOrgId())) {
            log.error("empCode或者orgId为空，不处理org_user数据");
            throw new BizException("userId或者orgId为空，不处理org_user数据");
        }
        SingleResponse<User> userResponse = userServiceI.getById(empCode);
        User user = userResponse.getData();
        User save = new User();
        Status status = (empInfoQueryRespDTO.getWorkingState() == 1 || empInfoQueryRespDTO.getWorkingState() == 0) ? Status.ENABLE:Status.DISABLE;
        if (user == null){
            save.setId(empCode);
            save.setStatus(status);
            save.setSourceId(deptId);
            save.setEmployeeNo(empCode);
            save.setPosition("");
            save.setOrgId(departmentServiceI.getById(deptId).getOrgId());
            save.setMainDepartmentId(deptId);
            save.setBaseUserId(empCode);
            save.setDeleted(false);
            //todo insert
        }else{
            BeanUtil.copyProperties(user, save);
            save.setStatus(status);
            save.setSourceId(deptId);
            save.setOrgId(departmentServiceI.getById(deptId).getOrgId());
            save.setMainDepartmentId(deptId);
            save.setModifiedTime(new Date());
            //todo update
        }
        log.info("org_user数据保存成功, result is : {}", JSON.toJSONString(save));

    }

    /**
     * 部门数据同步逻辑
     * @param departmentInfoDTO
     * @throws BizException
     */
    private void departmentSync(PcDepartmentInfoDTO departmentInfoDTO) throws BizException {
//        if (null == departmentInfoDTO) {
//            log.error("kafka部门数据为空");
//            throw new BizException("kafka部门数据为空");
//        }
//        String deptId = String.valueOf(departmentInfoDTO.getId());
//        String name = departmentInfoDTO.getDpmentName();
//        String parentId = departmentInfoDTO.getParentDpmentCode();
//
//        String parentId = null;
//        if (StringUtils.isNotEmpty(parentId)) {
//            Department parentDept = departmentServiceI.getDepartmentById(parentId);
//            if (null == parentDept){
//                log.error("sourceId[{}]代表的父部门不存在，无法创建", parentSourceId);
//                throw new BizException("未找到父部门数据");
//            } else {
//                parentId = parentDept.getId();
//            }
//        }
//
//        Department record = departmentService.getBySourceIdAndCorpId(deptSourceId, corpId);
//        Department department;
//        if (null == record) {
//            log.info("准备新增部门数据");
//            department = new Department();
//        } else {
//            log.info("准备更新部门数据");
//            department = record;
//            department.setModifiedTime(new Date());
//        }
//        department.setSourceId(deptSourceId);
//        department.setName(deptName);
//        department.setParentId(parentId);
//        department.setDeptType(DeptType.DEPT);
//        department.setCorpId(corpId);
//        department.setLeaf(true);
//        Department save = departmentService.save(department);
//        log.info("部门数据保存完成，结果为: {}", JSON.toJSONString(save));
    }

}
